package com.kaifamiao.reqeust;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;

/**
 * 1、Enumeration<String> getParameterNames()
 *      获得所有请求参数名称组成的 Enumeration 对象
 * 2、String getParameter(String name)
 *      根据请求参数的名称获得参数值
 * 3、String[] getParameterValues(String name)
 *      根据请求参数的名称获得参数值(若某个参数对应多个值时可以使用该方法)
 * 4、Map<String, String[]> getParameterMap()
 *      获得所有请求参数组成的Map集合，该Map以参数名为键，以参数值组成的数组为值
 */
@WebServlet("/param")
public class ParamServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html; charset=UTF-8" );
        PrintWriter out = response.getWriter();
        out.println( "<p>method: " + request.getMethod() + "</p>");
        // 获得 query string (国内通常被翻译成`查询字符串`)
        String qs = request.getQueryString();
        out.printf( "<p>query string: %s</p>\r\n", qs );

        Enumeration<String> paramNames = request.getParameterNames();
        Iterator<String> paramIterator = paramNames.asIterator();
        while( paramIterator.hasNext() ){
            String paramName = paramIterator.next();
            // 根据请求参数的名称获得参数值
            String paramValue = request.getParameter( paramName );
            out.printf( "<p>%s: %s</p>\r\n", paramName, paramValue );
        }

    }

}
